<template>
<div class="update-name">
<!-- 导航栏 -->
<van-nav-bar
  title="设置昵称"
  left-text="取消"
  @click-left="$emit('close')"
  right-text="完成"
  @click-right="onConfirm"
></van-nav-bar>
  <!-- /导航栏 -->

  <!-- 输入框 -->
  <div class="field-wrap">
<van-cell-group inset>
  <van-field
    v-model.trim="message"
    rows="2"
    autosize
    type="textarea"
    maxlength="7"
    placeholder="请输入昵称"
    show-word-limit
  />
</van-cell-group>
</div>
  <!-- /输入框 -->
</div>
</template>

<script>
import { ref } from 'vue'
import { updateUserProfile } from '@/api/user'
import { Toast } from 'vant'
export default {
  name: 'UpdateName',
  props: {
    name: {
      type: String,
      required: true
    }
  },
  setup (props, context) {
    const message = ref(props.name)
    async function onConfirm () {
      Toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁用背景点击
        duration: 0// 持续展示，直到下个Toast出现
      })
      try {
        if (!message.value.length) {
          Toast('昵称不能为空')
          return
        }
        await updateUserProfile({
          name: message.value
        })
        context.emit('confirmSuccess', message.value)
        Toast.success('更新成功')
      } catch (err) {
        if (err.response && err.response.status === 401) {
          Toast.fail('请重新登录')
        } else {
          Toast.fail('操作失败')
        }
      }
    }
    return {
      message,
      onConfirm
    }
  }
}
</script>

<style lang="less" scoped>
.field-wrap{
  padding: 20px;
}
</style>
